package com.kaifamiao.www.ioDemo.do0923;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        /**
         * 通过反射来创建对象
         * 1，使用Class对象的newInstance()方法来创建对象，JDK9开始已经被废除
         * 2，使用Constructor对象创建对象
         */
        //Instance 方法

        Class<Student> cl = Student.class;//获取对象，声明泛型

        Student stu = cl.newInstance();//创建对象，会调用无参构造

        System.out.println(stu);

        //使用Constructor对象的newInstance(args)方法

        //无参构造
        try {
            Constructor<Student> cons = cl.getConstructor();
            Student stu1 = cons.newInstance();
            System.out.println(stu1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        /**
         * newInstance方法的参数是可变参，对于getConstructor方法的参数
         */
        //有参构造
        try {
            Constructor<Student> cons1=cl.getConstructor(String.class,double.class,String.class);
            Student stu2 = cons1.newInstance("张三",80.88,"男");
            System.out.println(stu2);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


}
